<template>

  <div class="app-container">

    <el-row :gutter="20">

      <el-col :span="4">

        <el-card class="lay-box">

          <div v-if="paperData.camOn && paperData.camInterval > 0">
            <exam-cam
              :cam-on="paperData.camOn"
              :cam-interval="paperData.camInterval"
              :paper-id="paperData.id"
              @break="handleBreak"
            />
            <div class="cam-box">
              <strong>监控中</strong>
              确保您的正脸在摄像头范围内！
            </div>
          </div>

          <div v-for="type in paperData.groupList" :key="type.id">
            <div class="title">
              {{ type.title }} <span style="float: right; font-size: 12px">总{{ type.quCount }}题/共{{ type.totalScore }}分</span>
            </div>

            <div class="card-box">
              <div v-for="item in type.quList" :key="item.id" class="item" @click="handleCurrent(item)">
                <div :class="{num:true, 'right': item.answered && item.quId !== cardItem.quId, 'current': item.quId === cardItem.quId}">{{ item.sort }}</div>
                <div class="flag"><i v-if="item.mark" class="el-icon-s-flag" style="color: #ff0000" /></div>
              </div>
            </div>

          </div>

        </el-card>

      </el-col>

      <el-col :span="17">
        <el-card id="exam-body" class="lay-box">
          <qu-item-exam v-model="quData" @fill="handleFill" />
        </el-card>
      </el-col>

      <el-col :span="3">

        <el-card class="lay-box">

          <el-row :gutter="10" style="text-align: center; line-height: 30px">
            <el-col :span="24">
              剩余时间
            </el-col>
            <el-col :span="24">
              <exam-timer v-model="paperData.leftSeconds" @timeout="doHandler(0)" />
            </el-col>
            <el-col :span="24">
              <el-divider />
            </el-col>
            <el-col :span="24">
              <el-button type="warning" @click="handHandExam()">提交试卷</el-button>
            </el-col>

            <el-col v-if="paperData.actionOn && paperData.actionInterval>0" :span="24">
              <el-divider />
              <action-checker
                :action-on="paperData.actionOn"
                :action-interval="paperData.actionInterval"
                :trigger="actionTrigger"
                @break="doHandler(4)"
              />
              秒内无任何操作将自动交卷！
            </el-col>

            <el-col :span="24">
              <el-divider />
            </el-col>

            <el-col :span="24">
              <el-button :disabled="!showPrevious" icon="el-icon-back" @click="handleNext(-1)">上一题</el-button>
            </el-col>
            <el-col :span="24" style="padding-top: 20px">
              <el-button :disabled="!showNext" type="primary" @click="handleNext(1)">下一题<i class="el-icon-right el-icon--right" /></el-button>
            </el-col>
          </el-row>

        </el-card>

      </el-col>

    </el-row>

    <!-- 页面离开检测 -->
    <leave-checker
      v-if="paperData.leaveOn && paperData.leaveCount>0"
      :leave-on="paperData.leaveOn"
      :leave-check="paperData.leaveCheck"
      :leave-count="paperData.leaveCount"
      :paper-id="paperData.id"
      @break="handleBreak('因切屏次数超限，系统已强制交卷！')"
    />

    <!-- 在线状态 -->
    <exam-socket :exam-id="paperData.examId" platform="pc" />

    <!-- 动作检测 -->
    <event-control />

  </div>

</template>

<script>
import { paperDetail, quDetail, handExam, fillAnswer } from '@/api/paper/exam'
import screenfull from 'screenfull'
import QuItemExam from './components/QuItemExam'
import ExamTimer from './components/ExamTimer'
import LeaveChecker from './components/LeaveChecker'
import ActionChecker from './components/ActionChecker'
import ExamCam from './components/ExamCam'
import ExamSocket from '@/views/web/exam/components/ExamSocket'
import EventControl from '@/components/EventControl'
import watermark from '@/utils/watermark'
import { mapGetters } from 'vuex'

export default {
  name: 'ExamProcess',
  components: {
    EventControl,
    ExamSocket,
    ExamCam,
    ActionChecker,
    LeaveChecker,
    ExamTimer,
    QuItemExam
  },
  data() {
    return {

      pageLoading: false,

      showPrevious: false,
      showNext: true,

      // 试卷ID
      paperId: '',
      // 当前答题卡
      cardItem: {},
      allItem: [],
      // 当前试题内容
      quData: {
        answerList: []
      },
      // 试卷信息
      paperData: {
        leftSeconds: 99999
      },

      // 动作检测
      actionTrigger: 0
    }
  },

  computed: {
    ...mapGetters([
      'realName',
      'name',
      'mobile'
    ])
  },

  created() {
    const id = this.$route.params.id
    if (id !== undefined) {
      this.paperId = id
      this.fetchData(id)
    }
  },

  beforeDestroy() {
    // 移除水印
    watermark.remove()
  },

  methods: {

    // 填充答案回调
    handleFill(quData) {
      // 触发变化
      this.actionTrigger = new Date().getTime()

      fillAnswer(quData).then(res => {
        // 填充结果
        this.cardItem.answered = res.data.fill
        this.cardItem.mark = quData.mark
      })
    },

    /**
     * 统计有多少题没答的
     * @returns {number}
     */
    countNotAnswered() {
      let na = 0
      // 判断全部未答
      this.paperData.groupList.forEach(function(item) {
        item.quList.forEach(function(qu) {
          if (!qu.answered) {
            na += 1
          }
        })
      })
      return na
    },

    // 答题卡选定
    handleCurrent(item) {
      this.nextQu(item)
    },

    // 上一题下一题
    handleNext(num) {
      let index = 0
      for (let i = 0; i < this.allItem.length; i++) {
        if (this.allItem[i].id === this.quData.id) {
          index = i
        }
      }
      index += num
      this.nextQu(this.allItem[index])
    },

    doHandler(exState) {
      // 打开
      this.pageLoading = true

      // 交卷
      handExam({ id: this.paperId, exState: exState }).then(() => {
        // 退出全屏
        if (screenfull.isFullscreen) {
          screenfull.toggle()
        }

        setTimeout(() => {
          this.$router.push({ name: 'ShowExam', params: { id: this.paperId }})
        }, 500)

        this.pageLoading = false
      }).catch(() => {
        this.pageLoading = false
      })
    },

    // 交卷操作
    handHandExam() {
      const that = this

      const na = that.countNotAnswered()
      let msg = '确认要交卷吗？'

      if (na > 0) {
        msg = '您还有' + na + '题未作答，确认要交卷吗?'
      }

      that.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.doHandler(0)
      })
    },

    // 保存答案
    nextQu(item) {
      // 查找详情
      this.fetchQuData(item)
    },

    // 试卷详情
    fetchQuData(item) {
      // 触发变化
      this.actionTrigger = new Date().getTime()

      // 打开
      this.pageLoading = true

      // 获得详情
      this.cardItem = item

      // 查找下个详情
      const params = { paperId: this.paperId, quId: item.quId }
      quDetail(params).then(response => {
        this.quData = response.data
        this.pageLoading = false

        // 还原滚动位置
        document.querySelector('#exam-body').scrollTop = 0

        // 计算索引
        const last = this.allItem.length - 1
        this.showPrevious = this.quData.id !== this.allItem[0].id
        this.showNext = this.quData.id !== this.allItem[last].id
      }).catch(err => {
        // 试题被删除的情况
        if (err != undefined && err.message != undefined && err.message === '20010001') {
          // 回到首页
          setTimeout(() => {
            window.location.href = '/#/web/index?error'
          }, 1500)
        }
      })
    },

    // 试卷详情
    fetchData(id) {
      const params = { id: id }
      paperDetail(params).then(res => {
        // 试卷内容
        this.paperData = res.data

        // 已经考完了，不允许
        if (this.paperData.handState !== 0) {
          this.$router.push({ name: 'ShowExam', params: { id: this.paperData.id }})
        }

        const that = this

        // 展开全部题目
        this.paperData.groupList.forEach(function(item) {
          item.quList.forEach(function(qu) {
            that.allItem.push(qu)
          })
        })

        if (!that.allItem || that.allItem.length == 0) {
          that.$confirm('试卷内容出现问题，无法继续考试！', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          }).then(() => {
            // 出现异常情况
            window.location.href = '/#/web/index?error'
          })

          return
        }

        this.cardItem = that.allItem[0]

        // 水印开关
        if (this.paperData.waterMark) {
          // 出现在题干部分
          const dom = document.querySelector('#exam-body')
          watermark.set(dom, `${this.realName} ${this.mobile || this.name}`)
        }

        // 当前选定
        this.fetchQuData(this.cardItem)
      })
    },

    // 强制交卷后操作
    handleBreak(msg) {
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        showClose: false,
        showCancelButton: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'error'
      }).then(() => {
        // 出现异常情况
        this.$router.push({ name: 'ShowExam', params: { id: this.paperData.id }})
      })
    }

  }
}
</script>

<style scoped>

.lay-box{
  height: calc(100vh - 40px);
  overflow-y: auto;
}

  .cam-box{
    background: #0a84ff;
    color: #fff;
    margin-top: -5px;
    font-size: 6px;
    line-height: 20px;
    padding: 5px
  }

  .cam-box div{
    font-size: 10px;
    font-weight: 700;
  }

  .title{

    font-size: 14px;
    font-weight: 700;
    padding: 10px 0px 10px 0px;
  }

</style>

